<?php

/**
 * Ignus Framework
 *
 * @author Sergey Palyanov <sergey.palyanov@gmail.com>
 * @link http://code.google.com/p/ignus-php/
 * @license http://apache.org/licenses/LICENSE-2.0
 * @package Ignus
 * @subpackage Log
 * @since 0.1
 */

namespace Ignus\Log;

use Ignus\Log\Append\Appender;

/**
 * @category Ignus
 * @package Log
 * @since 0.1
 */
class LogManager
{
    /**
     * LogManager instance
     * @var LogManager
     */
    private static $instance;

    /**
     * Loggers' instances
     * @var array
     */
    private static $loggers = array();

    /**
     * Effective logging level
     * @var integer
     */
    private $level;

    /**
     * Appender class
     * @var Appender
     */
    private $appender = null;

    /**
     * @param string $level
     * @param Appender $appender
     * @return void
     */
    private function __construct($level)
    {
        $this->level = $level;
    }

    /**
     * @static
     * @param Appender $appender
     * @return void
     */
    public static function setAppender(Appender $appender)
    {
        if (self::$instance->appender != null)
            self::$instance->appender->finalize();
        self::$instance->appender = $appender;
    }

    /**
     * Initialize logging with logging level and appender
     * @param int $level Logging level
     * @param Appender $appender
     */
    public static function init($level)
    {
        self::$instance = new self($level);
    }

    /**
     * Factory for loggers creation
     * @param string $logger Logger name
     * @return Logger
     */
    public static function getLogger($name)
    {
        if (isset(self::$loggers[$name]))
            return self::$loggers[$name];

        return self::$loggers[$name] = new Logger(self::$instance, $name);
    }

    /**
     * Returns effective logging level
     * @return string
     */
    public function level()
    {
        return $this->level;
    }

    /**
     * @param array $entry Log entry
     * @return void
     */
    public function addEntry(array $entry)
    {
        $this->appender->append($entry);
    }

    /**
     * Finalize appender
     */
    public function __destruct()
    {
        if ($this->appender != null)
            $this->appender->finalize();
    }
}
